﻿using System;
using System.Collections;
using System.IO;
using System.Reflection;

namespace JCodeGen
{
    public class ResourcesLoader
    {
        private string fileName;

        Hashtable resources = new Hashtable();

        private void initialize()
        {
            string extension = System.IO.Path.GetExtension(fileName).ToLower();
            switch (extension)
            {
                case ".exe":
                case ".dll":
                    LoadResourcesFromAssemblyFile(fileName);
                    break;

                default:
                    throw new Exception("Unknown file format");
            }
        }

        private void LoadResourcesFromAssemblyFile(string fileName)
        {
            resources.Clear();

            Assembly assem = Assembly.LoadFrom(fileName);
            foreach (string resourceName in assem.GetManifestResourceNames())
            {
                Stream stream = assem.GetManifestResourceStream(resourceName);

                resources.Add(resourceName, stream);

                //char delimiter = '.';
                //int pos = resourceName.LastIndexOf(delimiter);
                //pos = resourceName.LastIndexOf(delimiter, pos - 1);
                //string resourceFile = resourceName.Substring(pos + 1);
                //resources.Add(resourceFile, stream);
            }
        }

        public Stream GetResource(string resourceName)
        {
            return (Stream) resources[resourceName];
        }

        public ResourcesLoader(string fileName)
        {
            this.fileName = fileName;

            initialize();
        }

        public ResourcesLoader()
            : this(System.Reflection.Assembly.GetExecutingAssembly().Location)
        {
        }
    }
}